package com.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.system.constant.HTTPStatus;
import com.system.entity.Role;
import com.system.entity.Teacher;
import com.system.entity.TeacherRole;
import com.system.mapper.TeacherMapper;
import com.system.response.Result;
import com.system.service.RoleService;
import com.system.service.TeacherService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.system.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 教师表 服务实现类
 * </p>
 *
 * @author zfc
 * @since 2023-04-20
 */
@Service
@PropertySource("classpath:config.properties")
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements TeacherService {

    @Autowired
    private TeacherMapper teacherMapper;

    @Autowired
    private RoleService roleService;

    @Value("${initial.password}")
    private String initialPassword;

    @Override
    public Teacher getTeacherByUserName(String username) {
        //这里用户名需要区分大小写，后续需要完善（暂未找到合适的解决方案）
        return teacherMapper.getTeacherByUserName(username);
    }

    @Override
    public boolean addTeahcer(Teacher teacher) {

        String md5SlitPassword = StringUtils.md5(initialPassword + "ZFCxhYH");

        teacher.setPassword(md5SlitPassword);
        return teacherMapper.insert(teacher) > 0;
    }

    @Override
    public Teacher selectTeahcerById(Integer id) {
        Teacher teacher = teacherMapper.selectOne(
                new LambdaQueryWrapper<Teacher>()
                        .eq(Teacher::getId, id)
        );
        return teacher;
    }

    @Override
    public Teacher selectTeahcerAllById(Integer id) {
        Teacher teacher = teacherMapper.selectOne(
                new LambdaQueryWrapper<Teacher>()
                        .eq(Teacher::getId, id)
        );
        teacher.setPassword("******");
        return teacher;
    }

    @Override
    public boolean updateTeacher(Teacher teacher) {
        return teacherMapper.updateById(teacher) > 0;
    }

    @Override
    public Result batchUpdateTeacherIsDelete(Integer[] ids, Integer isDelete) {
        //检查id的数量，如果超过50则提示批量执行最多50条
        if (ids.length>50){
            return new Result().setCode(HTTPStatus.BAD_REQUEST).setMessage("批量执行数量为50！");
        }
        List<Teacher> teacherList = new ArrayList<>();
        for (Integer id : ids) {
            //后续如果很教师有关联关系的需要在这里判断

            //1、如果用户绑定了角色，则该用户能不被删除
            TeacherRole newTR = new TeacherRole();
            newTR.setTeacherId(id);
            boolean boundRoles = roleService.checkTeacherBoundRoles(newTR);
            if (boundRoles) {
                return new Result().setCode(HTTPStatus.BAD_REQUEST).setMessage("存在用户绑定了角色，暂不能停用！");
            }

            //2、查询该用户是否存在
            Teacher teacher = teacherMapper.selectOne(new LambdaQueryWrapper<Teacher>().eq(Teacher::getId, id));
            if (teacher == null) {
                return new Result().setCode(HTTPStatus.BAD_REQUEST).setMessage("存在用户不存在");
            }
            //添加数据，待批量执行
            teacherList.add(new Teacher(id,isDelete));
        }

        boolean b = this.updateBatchById(teacherList, 50);
        if (!b){
            return new Result().setCode(HTTPStatus.BAD_REQUEST).setMessage("执行错误，请联系管理员！");
        }
        String statusStr = isDelete == 0 ? "恢复" : "停用";
        String txt = ids.length > 1 ? "批量":"";
        return new Result().setCode(HTTPStatus.SUCCESS).setMessage(txt+""+statusStr+"成功！");
    }

    @Override
    public Result batchDeleteTeacherById(Integer[] ids) {
        //这一块后续肯定有业务需要判断，比如教师如果有课程就不能删除...

        //将数组转化为list
        List<Integer> collect = Arrays.stream(ids).collect(Collectors.toList());
        boolean b = this.removeByIds(collect);
        if (!b){
            return new Result().setCode(HTTPStatus.BAD_REQUEST).setMessage("执行错误，请联系管理员！");
        }
        String txt = ids.length > 1 ? "批量":"";
        return new Result().setCode(HTTPStatus.SUCCESS).setMessage(txt+"删除成功！");
    }

    @Override
    public Result resetTeacherPwd(Teacher teacher) {

        if (teacher.getPassword()!=null && teacher.getPassword().length()<6){
            return new Result().setCode(HTTPStatus.BAD_REQUEST).setMessage("密码长度小于6位！");
        }

        //1、判断密码是否为空，如果为空就用默认的初始密码
        if (teacher.getPassword()==null || teacher.getPassword()==""){
            teacher.setPassword(StringUtils.md5(initialPassword + "ZFCxhYH"));
        }else {
            teacher.setPassword(StringUtils.md5(teacher.getPassword() + "ZFCxhYH"));
        }
        int i = teacherMapper.updateById(teacher);
        if (i<=0){
            return new Result().setCode(HTTPStatus.BAD_REQUEST).setMessage("执行错误，请联系管理员！");
        }
        return new Result().setCode(HTTPStatus.SUCCESS).setMessage("重置成功！");
    }

    @Override
    public PageInfo teacherLimit(Map<String, Object> maps) {
        Integer pageSize = (Integer) maps.get("pageSize");
        Integer pageNum = (Integer) maps.get("pageNum");
        PageHelper.startPage(pageSize, pageNum);
        List<Teacher> teacherList = teacherMapper.selectList(
                new LambdaQueryWrapper<Teacher>()
                        .eq(!StringUtils.isNull(maps.get("delete")), Teacher::getIsDelete, maps.get("delete"))
                        .like(!StringUtils.isNull(maps.get("name")), Teacher::getName, maps.get("name"))
                        .like(!StringUtils.isNull(maps.get("tel")), Teacher::getTel, maps.get("tel"))
                        .orderByAsc(Teacher::getCreateDate)
                        .select(
                                Teacher::getId,Teacher::getName,Teacher::getUsername,Teacher::getTel,
                                Teacher::getIsDelete,Teacher::getRemark,Teacher::getCreator,
                                Teacher::getCreateDate,Teacher::getModifier,Teacher::getModifyDate
                        )
        );
        //查询用户绑定的角色
        teacherList.forEach(teacher -> {
            Set<Role> roles = roleService.queryTeacherBoundRoles(teacher.getId());
            teacher.setRoleList(roles);
        });
        Integer count = teacherMapper.selectCount(
                new LambdaQueryWrapper<Teacher>()
                        .eq(!StringUtils.isNull(maps.get("delete")), Teacher::getIsDelete, maps.get("delete"))
                        .like(!StringUtils.isNull(maps.get("name")), Teacher::getName, maps.get("name"))
                        .like(!StringUtils.isNull(maps.get("tel")), Teacher::getTel, maps.get("tel"))
                        .orderByAsc(Teacher::getCreateDate)
        );

        PageInfo<Teacher> info = new PageInfo<>(teacherList);
        info.setSize(count);
        return info;
    }

    @Override
    public Result teacherAll() {
        List<Teacher> teacherList = teacherMapper.selectList(new LambdaQueryWrapper<Teacher>().select(Teacher::getId, Teacher::getName));

        return new Result().setCode(HTTPStatus.SUCCESS).setData(teacherList);
    }

    @Override
    public boolean upadteTeacherPassword(Teacher teacher) {
        String md5SlitPassword = StringUtils.md5(teacher.getPassword() + "ZFCxhYH");

        teacher.setPassword(md5SlitPassword);
        return updateTeacher(teacher);
    }

    @Override
    public boolean checkTeacherPasswordUnique(Teacher teacher) {
        String formerPassword = selectTeahcerById(teacher.getId()).getPassword();
        String md5SlitPassword = StringUtils.md5(teacher.getPassword() + "ZFCxhYH");
        boolean equals = formerPassword.equals(md5SlitPassword);
        return equals;
    }

    @Override
    public boolean checkFormerPasswordFlag(Teacher teacher, String formerPwd) {

        String md5SlitPassword = StringUtils.md5(formerPwd + "ZFCxhYH");

        String password = selectTeahcerById(teacher.getId()).getPassword();

        boolean equals = md5SlitPassword.equals(password);
        return equals;
    }

}
